<template>
  <el-form :inline="true" :model="formData" class="demo-form-inline">
    <el-form-item label="客户">
      <el-select placeholder="请选择客户" clearable v-model="formData.erpSupplier.supName">
        <el-option v-for="customer in customers" :key="customer.id" :label="customer.supName" :value="customer.supId" />
      </el-select>
    </el-form-item>
    <el-form-item label="单据编号">
      <el-input v-model="formData.number" placeholder="自动生成单据编号" readonly></el-input>
    </el-form-item>

    <el-form-item label="创建时间">
      <el-date-picker v-model="formData.createTime" type="datetime" placeholder="选择日期与时间" clearable class="input" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="updateData">保存</el-button>
    </el-form-item>


    <div class="user-index-body-form-btn-item">
      <div class="ant-row-flex" style="display: flex; align-items: center;">
        <div class="ant-col" style="margin-right: 10px;">
          <el-button type="primary" @click="addRow" class="ant-btn ant-btn-primary">
            <el-icon class="el-icon-left">
              <Plus />
            </el-icon>
            <span>插入行</span>
          </el-button>

        </div>
        <div class="ant-col" style="margin-right: 10px;">
          <el-button plain>扫码录入</el-button>
        </div>
        <div class="ant-col" style="margin-right: 10px;">
          <el-button plain v-perm:sale:sale_order:insert:documents="insert">
            <el-icon style="margin-right: 5px;">
              <Clock />
            </el-icon>
            历史单据
          </el-button>
        </div>
        <div class="ant-col">
          <el-button plain>
            <el-icon style="margin-right: 5px;">
              <Grid />
            </el-icon>
            导入明细
          </el-button>
        </div>
      </div>

      <el-table :data="tableData" show-summary style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column width="120">
          <template #default="{ row }">

            <el-button type="primary" class="ant-btn ant-btn-primary" style="margin-right: 10px;" plain
              v-perm:sale:sale_order:insert:Saleinorder="Saleinorder">
              <el-icon class="el-icon-left">
                <Plus />
              </el-icon>
            </el-button>
          </template>
        </el-table-column>

        <el-table-column label="条码" width="120" v-if="showIdColumn">
          <template #default="{ row }">
            <el-input v-model="row.headerId"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="id" width="120">
          <template #default="{ row }">
            <el-input v-model="row.id"></el-input>
          </template>
        </el-table-column>

        <el-table-column label="条码" width="120">
          <template #default="{ row }">
            <el-input v-model="row.barCode"></el-input>
          </template>
        </el-table-column>

        <el-table-column label="名称" width="120">
          <template #default="{ row }">
            <el-input v-model="row.materialName"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="规格" width="120">
          <template #default="{ row }">
            <el-input v-model="row.standard"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="库存" width="120">
          <template #default="{ row }">
            <el-input v-model="row.totalOperNumber"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="单位" width="120">
          <template #default="{ row }">
            <el-input v-model="row.commodityUnit"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="数量" width="120">
          <template #default="{ row }">
            <el-input v-model="row.operNumber"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="单价" width="120">
          <template #default="{ row }">
            <el-input v-model="row.wholesaledecimal"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="金额" width="120">
          <template #default="{ row }">
            <el-input v-model="row.allPrice"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="税率" width="120">
          <template #default="{ row }">
            <el-input v-model="row.taxRate"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="税额" width="120">
          <template #default="{ row }">
            <el-input v-model="row.taxMoney"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="价税合计" width="120">
          <template #default="{ row }">
            <el-input v-model="row.taxLastMoney"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="备注" width="100">
          <template #default="{ row }">
            <el-input v-model="row.remark"></el-input>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="index-body tb">

      <el-form-item label="优惠率：" style="margin-right: 120px;">
        <el-input v-model="formData.discount" style="width: 185px">
          <template #suffix>
            <span>%</span>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="收款优惠：" style="margin-right: 120px;">
        <el-input v-model="formData.discountMoney" style="width: 240px"></el-input>
      </el-form-item>
      <el-form-item label="优惠后金额：">
        <el-input v-model="formData.discountLastMoney" style="width: 240px"></el-input>
      </el-form-item>

    </div>

    <div class="index-body zb">
      <el-form-item label="结算账户：" style="margin-right: 120px;">
        <el-select clearable style="width: 200px; " placeholder="请选择客户" v-model="formData.erpAccount.name">
          <el-option v-for="account in accounts" :key="account.id" :label="account.name" :value="account.accId" />
        </el-select>
      </el-form-item>
      <el-form-item label="收取定金：" style="margin-right: 100px;">
        <el-input style="width: 240px"></el-input>
      </el-form-item>
    </div>

    <div class="ant-coloery" style="margin-right: 10px;">
      <el-form-item label="附件：">
        <el-button plain>
          <el-icon style="margin-right: 10px;">
            <MessageBox />
          </el-icon>上传附件
        </el-button>
      </el-form-item>
    </div>
  </el-form>
  <el-dialog :destroy-on-close="true" :title="title" v-model="visible" width="70%"
    style="margin-left: 350px;margin-top: 200px">
    <router-view @close="close" @saveSaleinorder="saveSaleinorder" :data="data"></router-view>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, defineEmits, defineProps } from 'vue';
import router from '@/router';
import request from '@/api/request';
import { ElMessage } from 'element-plus';
let props = defineProps(["data"]);
let emits = defineEmits(['close'])
let formData = ref({ ...props.data })
console.log(formData.value);
console.log(formData.value.erpSupplier.supId);

const visible = ref(false);
const title = ref("");
const data = ref({});
const ruleForm = ref({

});
console.log(ruleForm.value);

const close = () => {
  visible.value = false;
};
// 表格数据
const tableData = ref([
  {
    barCode: '',
    categoryName: '',
    color: '',
    commodityUnit: '',
    materialName: '',
    mfrs: '',
    model: '',
    sku: '',
    standard: '',
    totalIn: '',
    totalOperNumber: '',
    totalOut: '',
    wholesaledecimal: '',
    basicnumber: '',
    allprice: '',
    headerId: '', // 确保 headerId 被包含
    accId: '',
    id: '' // 确保 accId 被包含
  }
]);


const Saleinorder = (p) => {
  title.value = p.cname;
  visible.value = true;
  router.push(p.path);
}
const addRow = () => {
  tableData.value.push({
    barCode: '',
    categoryName: '',
    color: '',
    commodityUnit: '',
    materialName: '',
    mfrs: '',
    model: '',
    sku: '',
    standard: '',
    totalIn: '',
    totalOperNumber: '',
    totalOut: '',
    wholesaledecimal: '',
    basicnumber: '',
    allprice: '',
    headerId: '', // 确保新行有 headerId
    accId: '',
    id: ''
  });
};

console.log(formData.value.erpDepotItemList);

console.log(formData.value.erpDepotItemList[0].id);
console.log(formData.value.erpAccount.accId);
const loadData = () => {
  request({
    url: '/erpmaterialinventory/find',
    method: 'get',
    params: {
      headerId: formData.value.erpDepotItemList[0].id
    }
  }).then(res => {
    console.log(res);
    tableData.value = res.data.map((item, index) => ({
      ...item,
      id: saveid.value[index] ? saveid.value[index].id : '' // 将 saveid 中的 id 赋给 tableData
    }));
    console.log(tableData.value);
  }).catch(err => {
    console.error(err);
  });
};

loadData();
const saveid = ref([])
const loadDaidtaid = () => {
  request({
    url: '/sale/heftid',
    method: 'get',
    params: {
      headerId: formData.value.erpDepotItemList[0].id
    }
  }).then(res => {
    console.log(res);
    saveid.value = res.data; // 保存获取到的 id 集合
    loadData(); // 获取 saveid 后加载数据表
  }).catch(err => {
    console.error(err);
  });
};


loadDaidtaid();
const updateData = () => {
  const requestData = {
    erpDepotHead: {
      id: formData.value.erpDepotItemList[0].headerId,  // 从表单数据中获取头部信息
      organId: formData.value.erpSupplier.supId,       // 供应商ID
      creator: '63',                                   // 创建人ID
      accountId: formData.value.erpAccount.accId,     // 账户ID
      changeAmount: '0',                              // 变更金额
      totalPrice: tableData.value.reduce((total, r) => total + parseFloat(r.allPrice || 0), 0), // 计算总金额
      discount: formData.value.discount,               // 优惠率
      discountMoney: formData.value.discountMoney,     // 收款优惠
      discountLastMoney: formData.value.discountLastMoney, // 优惠后金额
      status: '0'                                      // 订单状态
    },
    erpDepotItems: tableData.value.map(r => ({       // 遍历表格数据，构造明细列表
      id: r.id,                                 // 项目ID
      materialId: r.mid,                           // 材料ID
      materialExtendId: r.aid,                     // 材料扩展ID
      materialUnit: r.commodityUnit,               // 材料单位
      sku: r.sku,                                   // SKU
      operNumber: r.operNumber,                     // 操作数量
      unitPrice: r.wholesaledecimal,               // 单价
      allPrice: r.allPrice,                         // 总金额
      remark: r.remark || '',                       // 备注
      taxRate: r.taxRate,                           // 税率
      taxMoney: r.taxMoney                          // 税额
    }))
  };

  console.log('请求数据:', requestData);  // 调试日志，输出请求数据

  request({
    url: '/sale/updateck',                          // 请求地址
    method: 'put',                                  // 请求方法
    params: { number: formData.value.number },       // 参数部分，传递单据编号
    data: requestData,                              // 请求体数据
    headers: { 'Content-Type': 'application/json' } // 请求头设置
  }).then(res => {
    console.log(res);                              // 成功时的响应处理
    ElMessage.success('提交成功');                  // 成功消息
  }).catch(err => {
    console.error(err);                             // 错误时的响应处理
    ElMessage.error('提交失败');                    // 错误消息
  });
};














const accounts = ref([]);
const loadAccounts = () => {
  request({
    url: '/basic/account/list',
    method: 'get'
  }).then(res => {

    accounts.value = res.data;
  }).catch(err => {
    console.error(err);
  });
};
loadAccounts();


// 



const customers = ref([]);
const loadCustomers = () => {
  request({
    url: '/basic/vendor/list',
    method: 'get'
  }).then(res => {
    customers.value = res.data;
  }).catch(err => {
    console.error(err);
  });
};
loadCustomers();







const insert = (p) => {
  title.value = p.cname;
  visible.value = true;
  router.push(p.path);
};
</script>

<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
